﻿using System;
using System.Drawing;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Taskbar;

namespace Icy.Douban.Radio
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            Shown += Main_Shown;
            Closed += Main_Closed;
            wbDouban.DocumentTitleChanged += WbDoubanDocumentTitleChanged;
        }

        void Main_Shown(object sender, EventArgs e)
        {
            if (!TaskbarManager.IsPlatformSupported) return;
            CreateJumpList();
            CreateTaskbar();
        }

        void Main_Closed(object sender, EventArgs e)
        {
            SendMSNMessage(false, "Office", "");
            TabbedThumbnail preview = TaskbarManager.Instance.TabbedThumbnail.GetThumbnailPreview(wbDouban);
            if (preview != null)
                TaskbarManager.Instance.TabbedThumbnail.RemoveThumbnailPreview(preview);
        }

        void WbDoubanDocumentTitleChanged(object sender, EventArgs e)
        {
            Text = wbDouban.DocumentTitle;
            SendMSNMessage(_isPlay, "Music", Text);
            TaskbarManager.Instance.TabbedThumbnail.SetThumbnailClip(Handle, new Rectangle(34, 34, 120, 120));

            ////自定义缩略图
            //TabbedThumbnail preview = new TabbedThumbnail(Handle, wbDouban);

            //TaskbarManager.Instance.TabbedThumbnail.AddThumbnailPreview(preview);

            //preview.TabbedThumbnailBitmapRequested +=
            //    (s, eventArgs) => eventArgs.TabbedThumbnail.SetImage(new Bitmap("icon.png", true));

            //preview.Tooltip = "This bitmap is created and returned on demand";
        }

        #region 任务栏状态按钮
        private ThumbnailToolbarButton _btnFav;
        private ThumbnailToolbarButton _btnDel;
        private ThumbnailToolbarButton _btnNext;
        private ThumbnailToolbarButton _btnControl;
        private bool _isPlay = true;

        private void CreateTaskbar()
        {
            _btnFav = new ThumbnailToolbarButton(Properties.Resources.Fav, "我喜欢");
            _btnFav.Click += btn_Click;

            _btnDel = new ThumbnailToolbarButton(Properties.Resources.Del, "不再播放");
            _btnDel.Click += btn_Click;

            _btnNext = new ThumbnailToolbarButton(Properties.Resources.Next, "跳过曲目");
            _btnNext.Click += btn_Click;

            _btnControl = new ThumbnailToolbarButton(Properties.Resources.Shut, "停止播放");
            _btnControl.Click += btnControl_Click;


            TaskbarManager.Instance.ThumbnailToolbars.AddButtons(Handle, _btnFav, _btnDel, _btnNext, _btnControl);
            TaskbarManager.Instance.SetOverlayIcon(Properties.Resources.Play, "正在播放");
            TaskbarManager.Instance.TabbedThumbnail.SetThumbnailClip(Handle, new Rectangle(34, 34, 120, 120));
        }

        private void CreateJumpList()
        {
            JumpList jl = JumpList.CreateJumpList();
            jl.KnownCategoryToDisplay = JumpListKnownCategoryType.Recent;

            JumpListCustomCategory catActions = new JumpListCustomCategory("链接");
            catActions.AddJumpListItems(
                new JumpListLink("http://icyflash.blog.sohu.com/", "Icyflash") { IconReference = new IconReference(Assembly.GetEntryAssembly().Location, 4) },
                new JumpListLink("http://douban.fm/", "豆瓣电台") { IconReference = new IconReference(Assembly.GetEntryAssembly().Location, 0) },
                new JumpListLink("http://douban.com/", "豆瓣"){ IconReference = new IconReference(Assembly.GetEntryAssembly().Location, 2) });
            jl.AddCustomCategories(catActions);
            jl.Refresh();
        }


        private void btnControl_Click(object sender, EventArgs e)
        {
            if (_isPlay)
            {
                _btnControl.Icon = Properties.Resources.Play;
                _btnControl.Tooltip = "播放";
                TaskbarManager.Instance.SetOverlayIcon(Properties.Resources.Shut, "停止播放中");
            }
            else
            {
                _btnControl.Icon = Properties.Resources.Shut;
                _btnControl.Tooltip = "停止播放";
                TaskbarManager.Instance.SetOverlayIcon(Properties.Resources.Play, "正在播放");
            }
            _isPlay=_btnNext.Enabled = _btnFav.Enabled = _btnDel.Enabled = !_isPlay;
            btn_Click(sender, e);
        }

        private void btn_Click(object sender, EventArgs e)
        {
            int x, y = 145;
            ThumbnailToolbarButton btn = (ThumbnailToolbarButton)sender;
            if (btn == _btnFav)
            {
                x = 282;
            }
            else if (btn == _btnDel)
            {
                x = 332;
            }
            else if (btn == _btnNext)
            {
                x = 378;
            }
            else
            {
                x = 391;
                y = 25;
            }
            if (WindowState == FormWindowState.Normal)
            {
                ControlFlash(x, y);
            }
            else
            {
                WindowState = FormWindowState.Normal;
                ControlFlash(x, y);
                WindowState = FormWindowState.Minimized;
            }
        }
        #endregion

        #region 按钮点击
        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);

        void ControlFlash(int x, int y)
        {
            IntPtr handle = this.wbDouban.Handle;
            StringBuilder className = new StringBuilder(100);
            while (className.ToString() != "Internet Explorer_Server") // The class control for the browser
            {

                handle = GetWindow(handle, 5); // Get a handle to the child window

                GetClassName(handle, className, className.Capacity);
            }

            IntPtr lParam = (IntPtr)((y << 16) | x); // The coordinates
            IntPtr wParam = IntPtr.Zero; // Additional parameters for the click (e.g. Ctrl)

            const uint downCode = 0x201; // Left click down code
            const uint upCode = 0x202; // Left click up code

            SendMessage(handle, downCode, wParam, lParam); // Mouse button down
            SendMessage(handle, upCode, wParam, lParam); // Mouse button up
        }
        #endregion

        #region 发送MSN消息
        [DllImport("user32", EntryPoint = "SendMessageA")]
        private static extern int SendMessage(int Hwnd, int wMsg, int wParam, int lParam);

        [DllImport("user32", EntryPoint = "FindWindowExA")]
        private static extern int FindWindowEx(int hWnd1, int hWnd2, string lpsz1, string lpsz2);

        private const short WM_COPYDATA = 74;

        public struct COPYDATASTRUCT
        {
            public int dwData;
            public int cbData;
            public int lpData;
        }
        public COPYDATASTRUCT data;

        public int VarPtr(object e)
        {
            GCHandle GC = GCHandle.Alloc(e, GCHandleType.Pinned);
            int gc = GC.AddrOfPinnedObject().ToInt32();
            GC.Free();
            return gc;
        }

        private void SendMSNMessage(bool enable, string category, string message)
        {
            string buffer = "\\0" + category + "\\0" + (enable ? "1" : "0") + "\\0{0}\\0" + message + "\\0\\0\\0\\0\0";
            int handle = 0;

            data.dwData = 0x0547;
            data.lpData = VarPtr(buffer);
            data.cbData = buffer.Length * 2;

            handle = FindWindowEx(0, handle, "MsnMsgrUIManager", null);
            if (handle > 0)
                SendMessage(handle, WM_COPYDATA, 0, VarPtr(data));
        }

        #endregion
    }
}
